package com.maikang.exammall.service;

import com.maikang.exammall.entity.Cart;
import com.maikang.exammall.entity.UserContext;
import com.maikang.exammall.entity.dto.CartDetailDTO;
import com.maikang.exammall.exception.BadRequestException;
import com.maikang.exammall.repository.CartRepository;
import com.maikang.exammall.repository.PackageRepository;
import com.maikang.exammall.util.BeanUtils;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static com.maikang.exammall.util.BeanUtils.getNullPropertyNames;


@Log4j2
@Service
public class CartService extends BaseService<Cart, Long, CartRepository> {
    @Autowired
    private PackageRepository pkgRepository;

    public Iterable<CartDetailDTO> findByUserId(Long userId, Pageable pageable) {
        return repository.findByUserId(userId, pageable);
    }

    @SneakyThrows
    @Transactional(rollbackFor = Exception.class)
    @Override
    public <S extends Cart> S save(S entity) {
        Long userId = UserContext.getUserId();
        entity.setUserId(userId);
        S target;
        Long id = entity.getPrimaryKey();
        if (id != null) {
            target = (S) repository.findByUserIdAndPkgIdAndId(userId, entity.getPkgId(), id);
            if (target == null) {
                throw new BadRequestException("user " + userId + "does not have this cart");
            }
            BeanUtils.copyProperties(entity, target, getNullPropertyNames(entity));
        } else {
            if (!pkgRepository.existsById(entity.getPkgId())) {
                throw new BadRequestException("package with id " + entity.getPkgId() + " does not exist");
            }
            target = entity;
        }
        return repository.save(target);
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteAllById(List<Long> ids) {
        repository.deleteAllById(ids);
    }
}
